/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package almacen;

import resources.local_connection;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.text.AttributeSet;
import javax.swing.text.PlainDocument;
import resources.queries;
import javax.swing.text.BadLocationException;

/**
 *
 * @author Tesla
 */
public class lotes extends javax.swing.JDialog {

    static Connection cn;
    int id_producto;
    int sucursal_id;
    String tipo;
    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
    public lotes(java.awt.Frame parent, boolean modal, int cd, int suc) {
 initComponents();
        if(!Almacen.giro.equals("Dental")){
            lblFecha.setVisible(false);
            fecha.setVisible(false);
        }
        tP1.setDocument(new LimitadorCaracteresFloat());
        tP2.setDocument(new LimitadorCaracteresFloat());
        tP3.setDocument(new LimitadorCaracteresFloat());
        labelProducto.setText("Producto ID: " + cd);
        sucursal_id = suc;
        id_producto = cd;
        cargarProveedores();
        
    }

    public static void cargarProveedores() {
        try {
            comboProveedor.removeAllItems();
            cn = local_connection.getconnect();
            PreparedStatement ps = (PreparedStatement) cn.prepareStatement("SELECT concat(nombre,' ',paterno,' ',materno) FROM personas WHERE tipo ='Proveedor'");
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                comboProveedor.addItem(rs.getString("concat(nombre,' ',paterno,' ',materno)"));
            }
        } catch (SQLException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        tP1 = new javax.swing.JTextField();
        tP2 = new javax.swing.JTextField();
        tP3 = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        spinnerCantidad = new javax.swing.JSpinner();
        jLabel5 = new javax.swing.JLabel();
        comboProveedor = new javax.swing.JComboBox();
        labelProducto = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        factura = new javax.swing.JTextField();
        lblFecha = new javax.swing.JLabel();
        fecha = new com.toedter.calendar.JDateChooser();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Lotes");
        setIconImage(new ImageIcon(getClass().getResource("/resources/logo_rayito.png")).getImage());
        setResizable(false);

        jButton1.setText("Guardar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Cancel");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel1.setText("Precio de producto:");

        jLabel2.setText("Precio de envio:");

        jLabel3.setText("Precio de empaque:");

        tP1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tP1ActionPerformed(evt);
            }
        });

        jLabel4.setText("Cantidad:");

        jLabel5.setText("Proveedor:");

        labelProducto.setText("Producto:");

        jButton3.setText("Agregar Proveedor");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jLabel6.setText("No de factura:");

        lblFecha.setText("Fecha de caducidad:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4)
                            .addComponent(jLabel5)
                            .addComponent(labelProducto)
                            .addComponent(jLabel6)
                            .addComponent(lblFecha))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(fecha, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(tP1)
                            .addComponent(tP2)
                            .addComponent(tP3)
                            .addComponent(spinnerCantidad)
                            .addComponent(comboProveedor, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(factura))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(labelProducto)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(factura, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(tP1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(tP2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(tP3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(spinnerCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(comboProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblFecha)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE)
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButton1)
                            .addComponent(jButton2)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(fecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {        
            String caduca;
            String name = String.valueOf(comboProveedor.getSelectedItem());
            int persona = 0;
            int cantidad = Integer.parseInt(spinnerCantidad.getValue().toString());
            if (cantidad < 1) {
                cantidad = 1;
            }
            if (tP1.getText().equals("")) {
                tP1.setText("0");
            }
            if (tP2.getText().equals("")) {
                tP2.setText("0");
            }
            if (tP3.getText().equals("")) {
                tP3.setText("0");
            }
            PreparedStatement ps = (PreparedStatement) cn.prepareStatement("SELECT * FROM personas WHERE concat(nombre,' ',paterno,' ',materno)='" + name + "' LIMIT 1");
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                persona = rs.getInt("id_persona");
            }
            caduca=(fecha.getDate()==null)?"0000-00-00":sdf.format(fecha.getDate());
            queries.doSyncQuery(cn, ps, "INSERT INTO lote(id_producto,cantidad,precio,envio,empaquetado,proveedor,sucursal,factura,caducidad,id_usuario) VALUES(" + id_producto + "," + cantidad + ",'" + tP1.getText() + "','" + tP2.getText() + "','" + tP3.getText() + "','" + persona + "'," + sucursal_id + ",'" + factura.getText() +"','"+caduca+"',"+Almacen.idUsuario+")");            
            this.dispose();
          //  System.out.println("INSERT INTO lote(id_producto,cantidad,precio,envio,empaquetado,proveedor,sucursal,factura,caducidad) VALUES(" + id_producto + "," + cantidad + ",'" + tP1.getText() + "','" + tP2.getText() + "','" + tP3.getText() + "','" + persona + "'," + sucursal_id + ",'" + factura.getText() +"','"+caduca+"')");
        // TODO add your handling code here:
        } catch (SQLException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);        }
    }//GEN-LAST:event_jButton1ActionPerformed
    
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        this.dispose();        // TODO add your handling code here:
    }//GEN-LAST:event_jButton2ActionPerformed
    
    private void tP1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tP1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_tP1ActionPerformed
    
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        (new agregarProvedor(this, true, 0)).setVisible(true);
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton3ActionPerformed
    class LimitadorCaracteresFloat extends PlainDocument {

        /**
         * Método al que llama el editor cada vez que se intenta insertar
         * caracteres. Sólo debemos verificar arg1, que es la cadena que se
         * quiere insertar en el JTextField
         */
        @Override
        public void insertString(int arg0, String arg1, AttributeSet arg2) throws BadLocationException {
            for (int i = 0; i < arg1.length(); i++) // si no es digit, volvemos
            {
                if (!(Character.isDigit(arg1.charAt(i)) || arg1.charAt(i) == '.')) {
                    return;
                }
            }

            // Si todos son digit, insertamos el texto en el JTextField
            super.insertString(arg0, arg1, arg2);
        }
    }
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private static javax.swing.JComboBox comboProveedor;
    private javax.swing.JTextField factura;
    private com.toedter.calendar.JDateChooser fecha;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel labelProducto;
    private javax.swing.JLabel lblFecha;
    private javax.swing.JSpinner spinnerCantidad;
    private javax.swing.JTextField tP1;
    private javax.swing.JTextField tP2;
    private javax.swing.JTextField tP3;
    // End of variables declaration//GEN-END:variables
}
